package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.ImageUploadResponse;
import com.luo.backend.service.FileUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/v1/upload")
@CrossOrigin
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传图片
     * 权限：只允许商家角色上传
     *
     * @param file 图片文件
     * @return 图片URL
     */
    @PostMapping("/image")
    @PreAuthorize("hasRole('MERCHANT')")
    public ResponseEntity<ApiResponse<ImageUploadResponse>> uploadImage(
            @RequestParam("file") MultipartFile file) {
        
        logger.info("接收到图片上传请求，文件名：{}, 大小：{} bytes", 
                    file.getOriginalFilename(), file.getSize());

        try {
            // 上传图片到 OSS
            String imageUrl = fileUploadService.uploadImage(file);

            // 返回成功响应
            ImageUploadResponse response = new ImageUploadResponse(imageUrl);
            logger.info("图片上传成功：{}", imageUrl);
            
            return ResponseEntity.ok(ApiResponse.success("上传成功", response));

        } catch (IllegalArgumentException e) {
            // 参数验证失败（文件类型、大小等）
            logger.warn("图片上传失败（参数错误）：{}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(400, e.getMessage()));

        } catch (Exception e) {
            // 其他错误（OSS上传失败等）
            logger.error("图片上传失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, "图片上传失败：" + e.getMessage()));
        }
    }
}



